package com.llynosy.interview.service;

import com.github.pagehelper.PageHelper;
import com.llynosy.interview.base.AbstractCommCRUD;
import com.llynosy.interview.mapper.ProblemMapper;
import com.llynosy.interview.mapper.ProblemTagMapper;
import com.llynosy.interview.po.Answer;
import com.llynosy.interview.po.Problem;
import com.llynosy.interview.po.ProblemTag;
import com.llynosy.interview.po.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProblemService  extends AbstractCommCRUD<Problem> {
    @Override
    public Problem findById(Long id) {
        return super.findById(id);
    }

    @Autowired
    private ProblemTagMapper problemTagMapper;

    @Override
    @Transactional
    public void add(Problem problem) {
        if(problem!=null&&problem.getTagIds()!=null){
            if(problem.getTagIds().length>0){
                for(Long tagId:problem.getTagIds()){
                    ProblemTag problemTag=new ProblemTag();
                    problemTag.setProblemId(problem.getId());
                    problemTag.setTagId(tagId);
                    problemTagMapper.insert(problemTag);
                }
            }
        }
        super.add(problem);
    }

    public Integer getNumberOfProblemsUnderTag(Long tagId){
        Integer numberOfProblemsUnderTag=((ProblemMapper)this.dao).countNumberOfProblemsUnderTag(tagId);
        return numberOfProblemsUnderTag;
    }

    @Value("${javainterview.pagesize}")
    private Integer pageSize;
    public List<Problem> getProblemByTag(Long tagId,Integer page){
        PageHelper.startPage(page,pageSize);
        List<Problem> problems=((ProblemMapper)this.dao).queryProblemByTag(tagId);
        return problems;
    }

    public List<Problem> getHotProblem(){
        return ((ProblemMapper)(this.dao)).queryHotProblem();
    }

    /**
     * 获得某个标签下热门问题
     *
     * @param tagId
     * @return List<Problem>
     */
    public List<Problem> getHotProblemBelowATag(Long tagId){
        return ((ProblemMapper)(this.dao)).queryHotProblemBelowATag(tagId);
    }

    public List<Problem> getLatestProblem(){
        return ((ProblemMapper)(this.dao)).queryLatestProblem();
    }

    public List<Problem> getProblemRelatedProblems(Long problemId){
        List<Problem> problems= ((ProblemMapper)(this.dao)).queryProblemRelatedProblems(problemId);
        return problems;
    }
}
